import { Data } from 'cydon'

/**
 * 简单路由解析
 * /p = { p: '' }
 * /p/1 = { p: 1 }
 * /p/1/related = {
 * 	p: {
 *		1: 'related'
 *	}
 * }
 */
export const parse = (url: string) => {
	const arr = url.substring(1).split('/')
	let a: string | Data = arr.pop()!,
		data: Data = {}
	while (arr.length) {
		data[arr.pop()!] = a
		a = data
		data = {}
	}
	return typeof a == 'string' ? { '/': a } : a
}

export type Params = number | {
	/** 搜索词 */
	search: string
	/** 排序 */
	order: string
	/** 偏移量 */
	offset: number
	/** 限制 */
	limit: number
}

/// 获取URL参数
export const parseURL = (hash: string): Params | null => {
	const pid = +hash
	if (pid)
		return pid
	const m = hash.match(/^\/([^/]+)\/([^/]+)\/(\d+)-(\d+)/)
	return m && {
		search: decodeURIComponent(m[1]),
		order: decodeURIComponent(m[2]),
		offset: +m[3],
		limit: +m[4] - +m[3]
	}
}

export const getURLHash = (p: Params) =>
	typeof p == 'number' ? `${p}` :
		`/${encodeURIComponent(p.search)}/${encodeURIComponent(p.order)
		}/${p.offset}-${p.offset + p.limit}`
